package ua.senfiron.vk.photo.viewer;

import ua.senfiron.vk.photo.viewer.util.NetworkUtilities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class ConnectivityChangeReceiver extends BroadcastReceiver{

    public static interface ConnectivityChangeListener {
        public void onNetworkConnected();
    }

    private static boolean sIsNetworkConnected = false;
    protected static ConnectivityChangeListener mListener;

    public static boolean isNetworkConnected() {
        return sIsNetworkConnected;
    }

    public static boolean isNetworkConnected(Context context) {
        sIsNetworkConnected = NetworkUtilities.isNetworkConnected(context);
        return sIsNetworkConnected;
    }

    public static void setListener(ConnectivityChangeListener listener)
    {
        mListener = listener;
    }

    public static void removeListener() {
        mListener = null;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        
        boolean newConnectionState = NetworkUtilities.isNetworkConnected(context);
        if(!sIsNetworkConnected 
                && newConnectionState
                && mListener != null) {
            Toast.makeText(context, "Internet is connected", Toast.LENGTH_SHORT).show();

            mListener.onNetworkConnected();
            mListener = null;
        }
        sIsNetworkConnected = newConnectionState;
    }
}
